package cn.webrx.bs.servlet;

import cn.webrx.bs.service.BookDao;
import cn.webrx.bs.service.BookDaoImpl;
import cn.webrx.bs.service.LinkDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>功能描述: </p>
 *
 * @author webrx
 * @version 1.0
 * @date 2020-09-09 12:02
 */
@WebServlet("/search")
public class Search extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String name = req.getParameter("search");
        int currpage = req.getParameter("page") == null ? 1 : Integer.parseInt(req.getParameter("page"));

        int pagesize = 2;
        BookDao bookdao = new BookDaoImpl();
        int recordcount = (int) bookdao.count("online and name like '%" + name + "%'");
        int pagecount = recordcount % pagesize == 0 ? recordcount / pagesize : recordcount / pagesize + 1;
        if (currpage < 1) currpage = 1;
        if (currpage > pagecount) currpage = pagecount;
        req.setAttribute("books", bookdao.searchByName(name, currpage, pagesize));
        StringBuilder pageinfo = new StringBuilder();
        pageinfo.append("<ul class=\"pagination justify-content-center\">");
        int ss = 1;
        int ee = 10;
        if(currpage>6){
            ss = currpage-5;
            ee = currpage+4;
        }
        if(currpage>1) pageinfo.append(String.format("<li class=\"page-item\"><a href=\"/search?page=%d%s\" class=\"page-link\">&laquo;上一页</a></li>",currpage-1,"&search="+name));
        for(int i=ss;i<=ee;i++){
            if(i>pagecount) break;
            if(currpage == i){
                pageinfo.append(String.format("<li class=\"page-item active\"><a href=\"/search?page=%d%s\" class=\"page-link\">%d</a></li>",i,"&search="+name,i));
                continue;
            }
            pageinfo.append(String.format("<li class=\"page-item\"><a href=\"/search?page=%d%s\" class=\"page-link\">%d</a></li>",i,"&search="+name,i));
        }
        if(currpage<pagecount)  pageinfo.append(String.format("<li class=\"page-item\"><a href=\"/search?page=%d%s\" class=\"page-link\">下一页&raquo;</a></li>",currpage+1,"&search="+name));
        pageinfo.append("</ul>");
        req.setAttribute("pageinfo",pageinfo);


        //友情链接
        req.setAttribute("links",new LinkDaoImpl().showAll());
        req.getRequestDispatcher("/home/search.ftl").forward(req, resp);
    }
}
